package com.welink.cmp.gatewayimpl.topotree;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.welink.cmp.dao.tree.ServiceTreeDaoService;
import com.welink.cmp.dao.tree.dataobejct.ServiceTreeDO;
import com.welink.cmp.domain.topotree.IServiceTreeGateway;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yanwei li create  2024-06-04 20:18
 */
@Component
@Primary
public class ServiceTreeGatewayImpl implements IServiceTreeGateway {

    @Resource
    private ServiceTreeDaoService serviceTreeDaoService;

    /**
     * @param hostId
     * @return
     */
    @Override
    public String getServiceTreeByHostId(Long hostId) {
        LambdaQueryWrapper<ServiceTreeDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ServiceTreeDO::getHostId,hostId)
                .eq(ServiceTreeDO::getStatus,1);
        final ServiceTreeDO one = serviceTreeDaoService.getOne(queryWrapper);
        if (one != null) {
            return one.getSrvTree();
        }
        return null;
    }

    /**
     * @param svcTree
     * @return
     */
    @Override
    public List<Long> getHostIdsByTree(String svcTree) {
        LambdaQueryWrapper<ServiceTreeDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ServiceTreeDO::getSrvTree,svcTree)
                .eq(ServiceTreeDO::getStatus,1);
        final List<ServiceTreeDO> list = serviceTreeDaoService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().map(ServiceTreeDO::getHostId).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * @param map
     * @return
     */
    @Override
    @Transactional
    public Boolean saveServiceTreeBatchByMap(Map<Long, String> map) {
        List<ServiceTreeDO> serviceTreeDOList = new ArrayList<>();
        LambdaUpdateWrapper<ServiceTreeDO> wrapper = Wrappers.lambdaUpdate(ServiceTreeDO.class);
        wrapper.in(ServiceTreeDO::getHostId,map.keySet());
        wrapper.set(ServiceTreeDO::getIsDel,1);
        serviceTreeDaoService.update(wrapper);

        map.forEach((key,value)->{
                    ServiceTreeDO serviceTreeDO = new ServiceTreeDO();
                    serviceTreeDO.setHostId(key);
                    serviceTreeDO.setSrvTree(value);
                    serviceTreeDOList.add(serviceTreeDO);
                }
        );

        Boolean result = serviceTreeDaoService.saveBatch(serviceTreeDOList);
        return result;
    }

}
